#include <iostream>
#include <signal.h>
#include <filesystem>
#include "../common/httplib.h"
#include "oj_control.hpp"

//该方法里面都有配置文件，如需调用请先使用对应类的初始化
#include <memory>
#include "../common/httpFunction.hpp"
using namespace httplib;

const std::string wwwroot = "./wwwroot/";
const std::string page404 = "404.html";
ns_control::Control ctrl;

void hander(int signo)
{
    ctrl.RecoveryHost();
}
int main()
{
    ns_http::Contentmap::Init();
    Server svr;
    //用户根据题目列表，获取内容
    //
    signal(SIGINT,hander);
    svr.Get("/all_questions",[](const Request& req,Response& resp){

        std::string html;
        if(!ctrl.AllQuestionsList(&html))
        {
            std::cerr<<html<<std::endl;
        }
        resp.set_content(html,"text/html;charset=utf-8"); 

    });
    svr.Get("/",[](const Request& req,Response& resp)
    {
        resp.set_content(ns_Util::FileUtil::ReadFileToString("./wwwroot/index.html"),"text/html;charset=utf-8");
    });

    svr.Get(R"(/question/(\d+))",[](const Request& req,Response& resp)
    {
        std::string number = req.matches[1];//C++的smatch，用于处理正则表达式的结果，下标1就是第一个字串，0下标是对应的整个正则表达式
        std::string html;
        if(ctrl.OneQuestionContent( number,&html) == false)
        {
            std::cerr<<html;
        }
        resp.set_content(html,"text/html;charset=utf-8");
    });
    svr.Post(R"(/judge/(\d+))",[](const Request& req,Response& resp){
        std::cout<<"收到Post判题请求\n";
        std::string number = req.matches[1];
        std::string result_json;
        ctrl.GetRunResult(number,req.body,&result_json);
        resp.set_content(result_json,"application/json;charset=utf-8");
        // resp.set_content("判定题号：" + number,"text/plain;charset=utf-8");
    });


    //对于没有设定的请求，httplib是接收到error_handdle里面处理了
    svr.set_error_handler([](const Request& req,Response& resp){
        std::string file_path = wwwroot + req.path;
        if(std::filesystem::exists(file_path))
        {
            resp.status = 200;
            size_t filesize = 0;
            std::shared_ptr<char> sptr  = ns_Util::FileUtil::ReadFileBinary(file_path,&filesize);
            resp.set_content(sptr.get(),filesize,ns_http::Contentmap::sub_type(std::filesystem::path(file_path).extension()));
        }
        else
        {
            resp.status = 404;
            resp.set_content(ns_Util::FileUtil::ReadFileToString(wwwroot+page404),"text/html;charset=utf-8");
            //错误处理
        }
    });
    
    svr.listen("0.0.0.0",8421);
    return  0;
}